package cnn.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;


@Configuration
public class DataSourceConfig {

    @Autowired
    protected Environment environment;

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.url}")
    private String dbUrl;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Bean(name = "hikariDataSource")
    @Primary
    public DataSource dataSource(){
        HikariDataSource datasource = new HikariDataSource();

        datasource.setDriverClassName(driverClassName);
        datasource.setJdbcUrl(dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setAutoCommit(true);
        datasource.setConnectionTestQuery("SELECT 1");
        datasource.addDataSourceProperty("dataSource.cachePrepStmts", "true");
        datasource.addDataSourceProperty("dataSource.prepStmtCacheSize", "250");
        datasource.addDataSourceProperty("dataSource.prepStmtCacheSqlLimit", "2048");
        datasource.addDataSourceProperty("dataSource.useServerPrepStmts", "true");

        return datasource;
    }
}
